<template>
  <el-container>
    <el-main>
      <el-form :model="form.model" :rules="form.rules" ref="formRef" label-width="100px">
        <el-form-item label="分类类型">
          <el-radio-group v-model="level" :disabled="modal.params.type == 'edit'" @change="changeType">
            <el-radio :label="1">一级分类</el-radio>
            <el-radio :label="2">二级分类</el-radio>
            <el-radio :label="3">三级分类</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="分类样式" v-if="level == 1">
          <div class="sa-flex">
            <div class="category-style" v-for="(img, index) in styleData.first" :key="index"
              @click="slectStyle(img.styleName)">
              <div class="category-image">
                <img :src="'./static/images/shop/category/' + img.styleName + '.png'" class="type-img"
                  :class="form.model.style == img.styleName ? 'activeBorder' : ''" />
                <el-icon v-show="form.model.style == img.styleName" class="badge">
                  <CircleCheckFilled />
                </el-icon>
              </div>
              <div class="sa-flex sa-row-center">
                <div class="category-title">样式{{ img.id }}</div>
                <el-popover placement="right" title="" :width="236" trigger="hover">
                  <template #reference>
                    <img class="category-icon" src="/static/images/shop/category/warning.png" />
                  </template>
                  <div class="hover-img">
                    <img :src="'./static/images/shop/category/' + img.styleName + '.png'" />
                  </div>
                </el-popover>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="分类样式" v-if="level == 2">
          <div class="sa-flex">
            <div class="category-style" v-for="(img, index) in styleData.second" :key="index"
              @click="slectStyle(img.styleName)">
              <div class="category-image" :class="form.model.style == img.styleName ? 'activeBorder' : ''">
                <img :src="'./static/images/shop/category/' + img.styleName + '.png'" class="type-img" />
                <el-icon v-show="form.model.style == img.styleName" class="badge">
                  <CircleCheckFilled />
                </el-icon>
              </div>
              <div class="sa-flex sa-row-center">
                <div class="category-title">样式{{ img.id }}</div>
                <el-popover placement="right" title="" :width="236" trigger="hover">
                  <template #reference>
                    <img class="category-icon" src="/static/images/shop/category/warning.png" />
                  </template>
                  <div class="hover-img">
                    <img :src="'./static/images/shop/category/' + img.styleName + '.png'" />
                  </div>
                </el-popover>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="分类样式" v-if="level == 3">
          <div class="sa-flex">
            <div class="category-style" v-for="(img, index) in styleData.third" :key="index"
              @click="slectStyle(img.styleName)">
              <div class="category-image" :class="form.model.style == img.styleName ? 'activeBorder' : ''">
                <img :src="'./static/images/shop/category/' + img.styleName + '.png'" class="type-img" />
                <el-icon v-show="form.model.style == img.styleName" class="badge">
                  <CircleCheckFilled />
                </el-icon>
              </div>
              <div class="sa-flex sa-row-center">
                <div class="category-title">样式{{ img.id }}</div>
                <el-popover placement="right" title="" :width="236" trigger="hover">
                  <template #reference>
                    <img class="category-icon" src="/static/images/shop/category/warning.png" />
                  </template>
                  <div class="hover-img">
                    <img :src="'./static/images/shop/category/' + img.styleName + '.png'" />
                  </div>
                </el-popover>
              </div>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.model.name" placeholder="请输入分类名称"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.model.description" placeholder="请输入描述"></el-input>
        </el-form-item>
        <el-form-item label="分类权重">
          <el-input v-model="form.model.weigh" type="number" :min="0" placeholder="请输入分类权重"></el-input>
        </el-form-item>
        <div class="head sa-flex sa-row-between">
          <div class="des">分类数据</div>
          <div class="btn">
            <a @click="addfirst" v-if="level">+ 插入一级分类</a>
          </div>
        </div>
        <div style="overflow: auto">
          <div class="custom-tree-header sa-flex">
            <div class="custom-tree-box sa-flex">
              <div class="expanded-width-id" v-if="props.modal.params.type == 'edit'"> ID </div>
              <div class="expanded-width-input">分类名称</div>
              <div class="expanded-width-image sa-flex sa-row-center"> 分类图片 </div>
              <div class="expanded-width-des">描述</div>
              <div class="expanded-width-sort">
                <el-popover placement="bottom" title="" width="120" trigger="hover">
                  <template #reference> 排序 </template>
                  <div class="popover-container">
                    权重以倒序排列，默认值为0，相同权重则以ID优先
                  </div>
                </el-popover>
              </div>
              <div class="expanded-width-operation">操作</div>
            </div>
          </div>
          <div class="sa-tree-table-content sa-flex">
            <el-tree :data="tree.data" ref="treeRef" node-key="id" default-expand-all :expand-on-click-node="false"
              :props="defaultProps">
              <template #default="{ node, data }">
                <div class="sa-flex drag-item" v-if="!(data.deleted && data.deleted == 1)">
                  <div class="expanded-width-id sa-flex" v-if="props.modal.params.type == 'edit'">
                    <span v-if="(data.id + '').indexOf('add') == -1 && (data.id + '').substring(0, 3) !== 'new'">{{
                      data.id
                    }}</span>
                  </div>

                  <div class="sa-flex expanded-width-input">
                    <div class="expanded-icon sa-flex" :class="operation(node.level)">
                      <div v-if="data.children && data.children.length > 0">
                        <el-icon v-if="node.expanded" @click="isexpanded(node)">
                          <SemiSelect />
                        </el-icon>
                        <el-icon v-if="!node.expanded" @click="isexpanded(node)">
                          <Plus />
                        </el-icon>
                      </div>
                    </div>
                    <div style="margin-left: 16px">
                      <el-input v-model="data.name" placeholder="请输入分类名称" />
                    </div>
                    <div class="append-title sa-m-l-12" v-if="node.level == 1 && level != 1">
                      <a @click="append(data)">+ 插入二级分类</a>
                    </div>
                    <div class="append-title sa-m-l-12" v-if="node.level == 2 && level == 3">
                      <a @click="append(data)">+ 插入三级分类</a>
                    </div>
                  </div>
                  <div class="sa-flex expanded-width-image sa-row-center">
                    <el-popover placement="bottom" :width="200" trigger="hover" content="建议尺寸：缩略图150X150">
                      <template #reference>
                        <div class="sa-flex icon-image">
                          <sa-uploader v-model="data.image" fileType="image" size="32"></sa-uploader>
                        </div>
                      </template>
                    </el-popover>
                  </div>
                  <div class="expanded-width-des">
                    <el-input v-model="data.description" placeholder="请输入分类描述" />
                  </div>
                  <div class="expanded-width-sort">
                    <el-input v-model="data.weigh" type="number" :min="0" placeholder="请输入排序" />
                  </div>
                  <div class="expanded-width-operation">
                    <span @click="hidden(data)">
                      <span v-if="data.status == 'normal'" style="color: #999999">隐藏</span>
                      <span v-else>显示</span>
                    </span>
                    <span @click="remove(node, data)" style="color: #ff4d4f; margin-left: 16px">删除</span>
                  </div>
                </div>
              </template>
            </el-tree>
          </div>
        </div>
      </el-form>
    </el-main>
    <el-footer class="sa-footer--submit">
      <el-button v-if="modal.params.type == 'add'" v-auth="'shop.admin.category.add'" type="primary"
        @click="confirm">保存</el-button>
      <el-button v-if="modal.params.type == 'edit'" v-auth="'shop.admin.category.edit'" type="primary"
        @click="confirm">更新</el-button>
    </el-footer>
  </el-container>
</template>
<script setup>
import { onMounted, reactive, ref, unref } from 'vue';
import { api } from './category.service';
import { cloneDeep } from 'lodash';

const emit = defineEmits(['modalCallBack']);
const props = defineProps({
  modal: {
    type: Object,
  },
});
// 添加 编辑 form
let formRef = ref(null);
const form = reactive({
  model: {
    name: '',
    style: 'first_one',
    description: '',
    weigh: 0,
    status: 'normal',
  },
  rules: {
    name: [{ required: true, message: '请输入分类名称', trigger: 'blur' }],
  },
});
const id = ref(0)
// 选择样式
const slectStyle = (e) => {
  form.model.style = e;
};
const treeRef = ref(null);

// ——————————————————————————————————
// tree 分类树状
const tree = reactive({
  data: [],
});
const defaultProps = {
  children: 'children',
  label: 'id',
};
//折叠
const isexpanded = (data) => {
  data.expanded = !data.expanded;
};
//改变分类类型
const changeType = (e) => {
  form.model.style = '';
  loopChildren(tree.data);
};
// 初始化数据
const level = ref(1);
let multIndex = ref(1);
function loopChildren(lists, lindex = 1) {
  multIndex.value = 1;
  multLevel(tree.data);
  if (multIndex.value <= level.value) {
    lindex += 1;
    if (lists.length == 0) {
      lindex -= 1;
      if (lindex <= level.value) {
        lists.push({
          id: 'new' + (id.value++),
          name: '',
          image: '',
          description: '',
          weigh: 0,
          status: 'normal',
        });
        loopChildren(lists, lindex);
      }
    } else {
      if (lindex <= level.value) {
        lists.forEach((k) => {
          if (!k.children) {
            k.children = [
              {
                id: 'new' + (id.value++),
                name: '',
                image: '',
                description: '',
                weigh: 0,
                status: 'normal',
              },
            ];
          }
          loopChildren(k.children, lindex);
        });
      }
    }
  } else if (multIndex.value > level.value) {
    lists.forEach((l) => {
      if (lindex == level.value) {
        delete l.children;
      } else {
        lindex += 1;
        if (l.children && l.children.length > 0) {
          loopChildren(l.children, lindex);
        }
      }
    });
  }
}
function multLevel(arr) {
  arr.forEach((a) => {
    if (a.children) {
      multIndex.value += 1;
      multLevel(a.children);
    }
  });
}

//添加一级分类
const addfirst = () => {
  tree.data.unshift({
    id: 'new' + (id.value++),
    name: '',
    status: 'normal',
    description: '',
    image: '',
    weigh: 0,
    children: [],
  });
};
// 更改tree 收缩padding
const operation = (id) => {
  if (id == 2) {
    return 'level-2';
  } else if (id == 3) {
    return 'level-3';
  }
};
const append = (data) => {
  const newChild = {
    id: 'new' + (id.value++),
    name: '',
    image: '',
    description: '',
    weigh: 0,
    status: 'normal',
  };
  if (!data.children) {
    data.children = [];
  }
  data.children.unshift(newChild);
};
//隐藏分类
const hidden = (data) => {
  if (data.status == 'normal') {
    data.status = 'hidden';
  } else {
    data.status = 'normal';
  }
};
//删除分类
const remove = (node, data) => {
  const parent = node.parent;
  const children = parent.data.children || parent.data;
  const index = children.findIndex((d) => d.id == data.id);
  if (children[index].children) {
    children[index].deleted = 1;
    children[index].children.forEach((i) => {
      i.deleted = 1;
      if (i.children) {
        i.children.forEach((j) => {
          j.deleted = 1;
        });
      }
    });
  } else {
    children[index].deleted = 1;
  }
  tree.data = [...tree.data]
};
// 样式类型
const styleData = {
  first: [
    { styleName: 'first_one', id: '一' },
    { styleName: 'first_two', id: '二' },
  ],
  second: [{ styleName: 'second_one', id: '一' }],
  third: [{ styleName: 'third_one', id: '一' }],
};
const loading = ref(false);
// 获取详情
async function getDetail(id) {
  loading.value = true;
  const { error, data } = await api.detail(id);
  if (error === 0) {
    form.model = data.category;
    tree.data = data.categories;
    if (data.category.style.substring(0, 1) == 'f') {
      level.value = 1;
    } else if (data.category.style.substring(0, 1) == 's') {
      level.value = 2;
    } else {
      level.value = 3;
    }
  }
  loading.value = false;
}

// 表单关闭时提交
function confirm() {
  unref(formRef).validate(async (valid) => {
    if (!valid) return;
    let submitTree = {
      categories: [],
    };
    tree.data.forEach(i => {
      if (i.id?.toString().substring(0, 3) === 'new') {
        delete i.id
      }
      if (i.children) {
        i.children.forEach(j => {
          if (j.id?.toString().substring(0, 3) === 'new') {
            delete j.id
          }
          if (j.children) {
            j.children.forEach(k => {
              if (k.id?.toString().substring(0, 3) === 'new') {
                delete k.id
              }
            })
          }
        })
      }
    })
    submitTree.categories = cloneDeep(tree.data);
    let submitForm = cloneDeep(form.model);
    let params = Object.assign(submitForm, submitTree);
    const { error } =
      props.modal.params.type == 'add'
        ? await api.add(params)
        : await api.edit(props.modal.params.id, params);
    if (error == 0) {
      emit('modalCallBack', {
        event: 'confirm',
        data: { uuID: props.modal.params.uuID },
      });
    }
  });
}
async function init() {
  if (props.modal.params.id) {
    await getDetail(props.modal.params.id);
  } else {
    loopChildren(tree.data);
  }
}
onMounted(() => {
  init();
});
</script>
<style lang="scss" scoped>
a {
  cursor: pointer;
}

//分类列表
.custom-tree-header {
  width: 100%;

  .custom-tree-box {
    flex: 1;
    position: unset;
    height: 40px;
    background: var(--sa-table-header-bg);
    font-size: 12px;
    font-weight: 500;
  }
}

.type-img {
  width: 100%;
  height: 100%;
  border-radius: 4px;
}

.head {
  width: 100%;
  height: 40px;
  background: var(--sa-table-header-bg);
  padding: 0 16px;

  .des {
    color: var(--sa-subtitle);
    font-size: 14px;
    font-weight: 500;
  }

  .btn {
    color: #806af6;
    font-size: 12px;
  }
}

.drag-item {
  width: 100%;
  height: 58px;
}

.expanded-width-id {
  width: 40px;
  padding-left: 16px;
}

.expanded-width-input {
  width: 380px;
  padding-left: 16px;
}

.expanded-width-image {
  width: 80px;
}

.icon-image {
  box-sizing: border-box;
  margin: 10px;
}

.expanded-width-des {
  width: 240px;
  padding-left: 16px;
}

.expanded-width-sort {
  width: 120px;
  padding-left: 16px;
}

.expanded-width-operation {
  width: 104px;
  padding-left: 16px;
}

.expanded-width-id,
.expanded-width-input,
.expanded-width-image,
.expanded-width-des,
.expanded-width-sort,
.expanded-width-operation {
  flex-shrink: 0;
}

.level-2 {
  padding-left: 40px;
}

.level-3 {
  padding-left: 80px;
}

:deep() {
  .el-radio-button__inner {
    padding: 0;
    border: none;
  }

  .el-popover.el-popper {
    padding: 8px;
  }

  .el-tree-node__content {
    width: 100%;
    height: 100%;
  }

  .el-tree-node__expand-icon {
    display: none;
  }

  .el-tree-node__content {
    padding-left: 0 !important;
  }

  .card-item {
    position: relative;
    overflow: hidden;
    width: 32px !important;
    height: 32px !important;
    color: var(--sa-subtitle);
    border: 1px solid var(--sa-border);
    border-radius: 4px;

    .image-overlay {
      width: 32px !important;
      height: 32px !important;
      position: absolute;
      top: 0;
      left: 0;
      background: var(--sa-basic-mask-background);
      color: var(--sa-basic-mask-color);
      display: none;

      i {
        font-size: 16px;
        cursor: pointer;
      }
    }

    &:hover {
      .image-overlay {
        display: flex;
      }
    }
  }

  .upload-icon {
    width: 32px !important;
    height: 32px !important;
    background: var(--sa-background-assist);
    border: 1px dashed var(--sa-border);
    border-radius: 4px;
    cursor: pointer;

    i {
      color: var(--sa-place);
      font-size: 14px !important;
    }
  }
}

.el-tree {
  flex: 1;
  position: unset;
}

.append-title {
  color: var(--el-color-primary);
}

.category-style {
  margin-right: 24px;
}

.category-image {
  width: 78px;
  height: 124px;
  display: flex;
  position: relative;
  border-radius: 4px;
}

.activeBorder {
  border: 1px solid var(--el-color-primary);
}

.badge {
  color: var(--el-color-primary);
  width: 16px;
  height: 16px;
  line-height: 16px;
  text-align: center;
  border-radius: 50%;
  font-weight: 600;
  font-size: 14px;
  position: absolute;
  top: -8px;
  right: -8px;
}

.category-title {
  font-size: 12px;
  line-height: 14px;
  color: var(--sa-font);
  margin-right: 4px;
  margin-top: 8px;
}

.hover-img {
  width: 220px;
  height: 350px;
  display: flex;
}

.category-icon {
  width: 14px;
  height: 14px;
  margin-top: 8px;
}
</style>
